<template>
  <div class="departments-container">
    <div class="page-header">
      <h2 class="page-title">操作日志</h2>
    </div>
    
    <div class="filter-section">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="IP地址">
          <el-input
            v-model="filterForm.ipAddress"
            placeholder="请输入IP地址"
            clearable
            @clear="handleFilter"
          />
        </el-form-item>
        
        <el-form-item label="请求路径">
          <el-input
            v-model="filterForm.path"
            placeholder="请输入请求路径"
            clearable
            @clear="handleFilter"
          />
        </el-form-item>
        
        <el-form-item label="请求时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleFilter"
            style="width: 380px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
          <el-button type="success" @click="handleExport">
            <el-icon><Download /></el-icon>导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card class="content-card">
      <el-table
        v-loading="loading"
        :data="logsList"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" sortable />
        <el-table-column prop="request_time" label="请求时间" width="180" sortable>
          <template #default="scope">
            {{ formatDateTime(scope.row.request_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="ip_address" label="IP地址" width="140" />
        <el-table-column prop="path" label="请求路径" min-width="180" show-overflow-tooltip />
        <el-table-column prop="method" label="请求方法" width="100">
          <template #default="scope">
            <el-tag :type="getMethodType(scope.row.method)">
              {{ scope.row.method }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status_code" label="状态码" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status_code)">
              {{ scope.row.status_code }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="browser" label="浏览器" width="120" />
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="viewDetail(scope.row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="请求日志详情"
      width="700px"
    >
      <div v-if="currentDetail" class="log-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="ID">{{ currentDetail.id }}</el-descriptions-item>
          <el-descriptions-item label="请求时间">{{ formatDateTime(currentDetail.request_time) }}</el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ currentDetail.ip_address }}</el-descriptions-item>
          <el-descriptions-item label="浏览器">{{ currentDetail.browser }}</el-descriptions-item>
          <el-descriptions-item label="请求方法">
            <el-tag :type="getMethodType(currentDetail.method)">
              {{ currentDetail.method }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态码">
            <el-tag :type="getStatusType(currentDetail.status_code)">
              {{ currentDetail.status_code }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="请求路径" :span="2">{{ currentDetail.path }}</el-descriptions-item>
          <el-descriptions-item label="User Agent" :span="2">{{ currentDetail.user_agent }}</el-descriptions-item>
        </el-descriptions>

        <div v-if="currentDetail.params" class="params-section">
          <h4>请求参数</h4>
          <pre>{{ formatJson(currentDetail.params) }}</pre>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh, Download } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getRequestLogs, getRequestLogDetail, exportRequestLogs } from '@/api/logs'
import { formatDateTime } from '../utils/format'

// 日志列表数据
const loading = ref(false)
const logsList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)



// 筛选表单
const filterForm = reactive({
  ipAddress: '',
  path: '',
  method: '',
  statusCode: '',
  dateRange: []
})

// 详情对话框
const detailDialogVisible = ref(false)
const currentDetail = ref(null)

// 获取日志列表
const fetchLogsList = async () => {
  loading.value = true
  try {
    // 构建请求参数
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      ip_address: filterForm.ipAddress,
      path: filterForm.path,
      method: filterForm.method
    }
    
    // 如果有状态码，转换为整数
    if (filterForm.statusCode) {
      params.status_code = parseInt(filterForm.statusCode, 10)
    }
    
    // 添加日期范围
    if (filterForm.dateRange && filterForm.dateRange.length === 2) {
      params.start_date = filterForm.dateRange[0]
      params.end_date = filterForm.dateRange[1]
    }
    
    try {
      const response = await getRequestLogs(params)
      if (response.code === 200) {
        // 正确访问API返回的数据
        logsList.value = response.data || []
        // 设置总数
        total.value = response.total || 0
      } else {
        ElMessage.error(response.message || '获取日志列表失败')
        logsList.value = []
        total.value = 0
      }
    } catch (error) {
      console.error('API请求失败', error)
      ElMessage.error('获取日志列表失败')
      logsList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取日志列表失败:', error)
    ElMessage.error('获取日志列表失败')
    logsList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchLogsList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchLogsList()
}

// 筛选器处理
const handleFilter = () => {
  currentPage.value = 1
  fetchLogsList()
}

// 重置筛选器
const resetFilter = () => {
  filterForm.ipAddress = ''
  filterForm.path = ''
  filterForm.method = ''
  filterForm.statusCode = ''
  filterForm.dateRange = []
  currentPage.value = 1
  fetchLogsList()
}

// 查看详情
const viewDetail = async (row) => {
  try {
    loading.value = true
    const response = await getRequestLogDetail(row.id)
    if (response.code === 200) {
      currentDetail.value = response.data
      detailDialogVisible.value = true
    } else {
      ElMessage.error(response.message || '获取日志详情失败')
    }
  } catch (error) {
    console.error('获取日志详情失败:', error)
    ElMessage.error('获取日志详情失败')
  } finally {
    loading.value = false
  }
}

// 格式化JSON
const formatJson = (json) => {
  if (!json) return ''
  try {
    if (typeof json === 'string') {
      return JSON.stringify(JSON.parse(json), null, 2)
    }
    return JSON.stringify(json, null, 2)
  } catch (error) {
    return json.toString()
  }
}

// 获取请求方法对应的标签类型
const getMethodType = (method) => {
  switch (method) {
    case 'GET': return 'success'
    case 'POST': return 'primary'
    case 'PUT': return 'warning'
    case 'DELETE': return 'danger'
    default: return 'info'
  }
}

// 获取状态码对应的标签类型
const getStatusType = (statusCode) => {
  if (statusCode >= 200 && statusCode < 300) return 'success'
  if (statusCode >= 400 && statusCode < 500) return 'warning'
  if (statusCode >= 500) return 'danger'
  return 'info'
}

// 导出日志
const handleExport = async () => {
  try {
    // 构建请求参数，与筛选参数相同
    const params = {
      ip_address: filterForm.ipAddress,
      path: filterForm.path,
      method: filterForm.method
    }
    
    // 如果有状态码，转换为整数
    if (filterForm.statusCode) {
      params.status_code = parseInt(filterForm.statusCode, 10)
    }
    
    // 添加日期范围
    if (filterForm.dateRange && filterForm.dateRange.length === 2) {
      params.start_date = filterForm.dateRange[0]
      params.end_date = filterForm.dateRange[1]
    }
    
    ElMessage.info('正在导出数据，请稍候...')
    
    try {
      const response = await exportRequestLogs(params)
      
      // 对于blob响应，直接使用response
      // 创建下载链接
      const url = window.URL.createObjectURL(new Blob([response]))
      const link = document.createElement('a')
      link.href = url
      
      // 设置文件名，使用当前日期
      const date = new Date()
      const fileName = `请求日志_${date.getFullYear()}${(date.getMonth() + 1).toString().padStart(2, '0')}${date.getDate().toString().padStart(2, '0')}.csv`
      link.setAttribute('download', fileName)
      
      // 触发下载
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      ElMessage.success('导出成功')
    } catch (error) {
      console.error('导出失败:', error)
      ElMessage.error('导出失败，请稍后重试')
    }
  } catch (error) {
    console.error('导出日志失败:', error)
    ElMessage.error('导出失败')
  }
}

onMounted(() => {
  fetchLogsList()
})
</script>

<style lang="scss" scoped>
.request-logs-container {
  padding: 20px;
  margin: 0;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.filter-section {
  margin-bottom: 20px;
  
  .filter-form {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.log-detail {
  .params-section {
    margin-top: 20px;
    
    h4 {
      font-size: 16px;
      margin-bottom: 10px;
    }
    
    pre {
      background-color: #f5f7fa;
      padding: 10px;
      border-radius: 4px;
      font-family: monospace;
      overflow: auto;
      max-height: 300px;
    }
  }
}

// 下拉选项样式
:deep(.el-select-dropdown__item) {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  
  .el-tag {
    margin-right: 8px;
    min-width: 60px;
    text-align: center;
  }
  
  .option-label {
    margin-left: 5px;
  }
}
</style> 